import Taro ,{ Component } from '@tarojs/taro'
import { View , Image , Text ,Ad , Canvas ,Button} from '@tarojs/components'
import { AtAvatar ,AtFloatLayout} from 'taro-ui'

import './carDetail.scss'

import default_head from '../../image/ic_header_default.png'
import start_icon from '../../image/ic_start.png'
import end_icon from '../../image/ic_end.png'
import time_icon from '../../image/ic_time.png'
import passanger_icon from '../../image/ic_people.png'

import {base_url} from "../../network/config";

import moment from 'moment';

import DataManager from '../../utils/DataManager.js'

import DetailToolBar from '../../component/DetailToolBar/detailToolBar.js';
import BasePage from "../basePage";
import {STORAGE_KEY} from "../../utils/const";

export default class CarDetail extends BasePage {

  config = {
    navigationBarTitleText: '车程详情'
  }

  defaultProps = {
    carId:'',
    startPlace : '',
    endPlace : '',
    publishTime: '',
    goTime: '',
    tel:'',
    peopleCount:'',
    note:'',
  }

  constructor() {
    super(...arguments)
    this.state={
      carDetailData:{},
      showAd:true,
      weixinCodeImage:'',
      shareTempFilePath:'',
      screenWidth:Number,
      screenHeight:Number,
      headImage:'',
      shareShow:false,
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentWillMount () {
    let systemInfo = Taro.getSystemInfoSync();
    this.setState({
      screenWidth:systemInfo.windowWidth,
      screenHeight:systemInfo.windowHeight,
    })

    this.carId = this.$router.params.carId;

    if (Taro.getStorageSync(STORAGE_KEY.SCENE)){
      this.carId = Taro.getStorageSync(STORAGE_KEY.SCENE);
      Taro.setStorageSync(STORAGE_KEY.SCENE, ''); //  scene只使用一次  否则进入其他详情id会错乱
    }

    let shareUserId = this.$router.params.shareUserId;

    if (shareUserId && DataManager.getUserId() != shareUserId){ // 保证自己的userID 和分享人 的userId 不一致 否则会出现自己点自己分享的链接问题
      Taro.setStorageSync(STORAGE_KEY.SHARE_USER_ID , shareUserId);
    }
  }

  componentDidMount(){
    this.loadCarDetail();
  }

  onShareAppMessage(options){
    console.log('---car-----options=======' + JSON.stringify(options))
    let _this = this;
    if (options.from == 'button'){
      // 转发成功
      console.log("转发成功:" + JSON.stringify(res));
      let url = base_url + 'rest/user/share/save';
      Taro.request({
        url:url,
        data: {
          token:DataManager.getToken(),
          platform:'android_c',
          weixinId:DataManager.getWeiXinId(),
          loginChannel:'c',
          appId:'KC876D98B30UA40CJSNHI689FB33SDW',
          digest : 'dda484557c12febe48139d8f44051c13',
          id:_this.carId,
          type:2,
        },
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        success(res) {
        }
      })
      return {
        path: `/pages/car/carDetail?carId=` + _this.carId + `&shareUserId=` + DataManager.getUserId(),
      }
    }
  }

  loadCarDetail(){
    let _this = this;

    let url = base_url + 'stateless/car/carDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        id:_this.carId
      },
      method: 'GET',
      success(res) {

        if (res.data.data && res.data.data.headUrl) {
          Taro.downloadFile({
            url:res.data.data.headUrl,
            success: function (res2) {
              console.log(res2);
              _this.setState({
                headImage:res2.tempFilePath
              })
            }
          })
        }

        _this.setState({
          carDetailData:res.data.data,
        })
      }
    })
  }

  onSharePost = () =>{

    let pageData = 'pages/car/carDetail';

    let _this = this;
    let url = base_url + 'stateless/weixin/code/weixinCodeDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        businessId:_this.carId,
        businessType:2,
        page:pageData
      },
      method: 'GET',
      success(res) {
        console.log('weixinCode-----' + JSON.stringify(res))
        if (res.data && res.data.data && res.data.data.weixinCode){
          Taro.showLoading({
            title : '图片生成中...'
          });
          Taro.downloadFile({
            url:res.data.data.weixinCode,
            success: function (res2) {
              console.log('this.state.weixinCodeImag =======' +res2.tempFilePath)
              _this.setState({
                weixinCodeImage:res2.tempFilePath
              })
              setTimeout(function () {
                Taro.hideLoading();
                _this.createPoster();
              } , 200)
            },
          })
        }
      }
    })
  }

  createPoster(){

    let midX = (this.state.screenWidth - 80) / 2

    let that = this;
    const ctx = Taro.createCanvasContext('share')

    let peopleCount;
    let typeName;
    let typeColor;
    if (this.state.carDetailData.type == 0){
      peopleCount = '乘车人数：' + this.state.carDetailData.peopleCount + '人';
      typeName = '人找车';
      typeColor = '#4395f5'
    } else if (this.state.carDetailData.type == 1) {
      peopleCount = '提供座位：' + this.state.carDetailData.peopleCount + '个';
      typeName = '车找人';
      typeColor = 'cyan';
    }
    let address = this.state.carDetailData.startAddress + ' -- ' + this.state.carDetailData.tagAddress;
    let goTime = '出发时间：' + this.stringDataFormat(moment(this.state.carDetailData.startDate).format('MM-DD HH:mm'));
    let intro = this.state.carDetailData.intro ? '备注：' + this.state.carDetailData.intro : '';
    let contract = '联系人：' + this.state.carDetailData.userName;
    let contractPhone = '联系电话：' + this.state.carDetailData.mobile;


    this.roundRect(ctx , 0 , 40 , this.state.screenWidth,500,10 , 'white');
    ctx.drawImage(this.state.weixinCodeImage ,20,350,100,100)

    ctx.draw(true);
    console.log('address===========' + address)
    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(address, 90, 95);
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(goTime, 20, 135);
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(peopleCount, 20, 175);
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(contract, 20, 215);
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(contractPhone, 20, 255);
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    if (intro){
      this.drawText(ctx,intro.replace('\n',' ') ,20 , 295, 148 , this.state.screenWidth - 60)
    }

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('长按识别图中二维码',
      140, 380)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('查看找车详情信息',
      140, 420)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);


    let w = ctx.measureText(typeName).width;
    this.roundRect(ctx , 20 , 80 , w + 20, 24 ,2 , typeColor);

    ctx.setFontSize(14);
    ctx.setFillStyle('white');
    ctx.fillText(typeName, 25, 95)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    //
    // ctx.setFontSize(18);
    // ctx.setFillStyle('#333333');
    // ctx.fillText(this.state.carDetailData.userName,
    //   115, 85)
    // ctx.fill();
    // ctx.restore();
    // ctx.draw(true);
    //
    // ctx.setFontSize(14);
    // ctx.setFillStyle('#436EEE')
    // ctx.fillText(peopleCount,
    //   115, 130)
    // ctx.fill();
    // ctx.restore();
    // ctx.draw(true);
    //
    // let content = this.state.carDetailData.startAddress + ' -- ' + this.state.carDetailData.tagAddress +
    //             '  出发时间：' + this.stringDataFormat(moment(this.state.carDetailData.startDate).format('MM-DD HH:mm'));
    //
    // this.drawText(ctx,content.replace('\n',' ') ,20 , 170, 148 , this.state.screenWidth - 60)
    //
    // ctx.arc(60, 100, 40, 0, Math.PI * 2)
    // ctx.clip();
    // ctx.drawImage(this.state.headImage,20,60,80,80);
    // ctx.restore();
    // ctx.draw(true);

    setTimeout(function () {
      Taro.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 667,
        canvasId: 'share',
        quality:1,
        success: function (res) {
          if (!res.tempFilePath) {
            Taro.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          } else {
            that.setState({
              shareTempFilePath: res.tempFilePath,
              shareShow:true
            })

            // let imageArray = [];
            // imageArray.push(res.tempFilePath);
            //
            // console.log('imagearray========' + imageArray[0])
            //
            // Taro.previewImage({
            //   urls:imageArray
            // })
          }
        }
      })
    } , 200)
  }

  /**
   *
   * @param {CanvasContext} ctx canvas上下文
   * @param {number} x 圆角矩形选区的左上角 x坐标
   * @param {number} y 圆角矩形选区的左上角 y坐标
   * @param {number} w 圆角矩形选区的宽度
   * @param {number} h 圆角矩形选区的高度
   * @param {number} r 圆角的半径
   */
   roundRect(ctx, x, y, w, h, r , color) {
    // 开始绘制
    ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.setFillStyle(color)
    // ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)

    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
    ctx.restore();
    ctx.draw(true);

  }


  drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    ctx.setFontSize(14);
    ctx.setFillStyle('#666666')

    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      console.log('line-------------' + lineWidth + '    ' + canvasWidth)
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 18; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  }

  saveSharePic = () =>{
    Taro.saveImageToPhotosAlbum({
      filePath: this.state.shareTempFilePath,
      success(res) {
        console.log("保存图片成功")
        console.log(res)
        Taro.showToast({
          title: '保存成功',
          duration: 2000
        })
      },
      fail(err) {
        console.log('失败')
        console.log(err)

        if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
          Taro.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败，给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      }
    })
  }

  onShareClose = () =>{
    this.setState({shareShow:false})
  }

  makePhoneCall = (phoneNumber) =>{
    Taro.makePhoneCall({
      phoneNumber : phoneNumber
    })
  }

  stringDataFormat(value){
    return value ? value : '';
  }

  onAdError = (e) =>{
    if (e){
      this.setState({
        showAd:false
      })
    }
  }

  onAdLoad = () => {
    this.setState({
      showAd:true
    })
  }

  render() {
    let startPlace = '出发地点：' + this.stringDataFormat(this.state.carDetailData.startAddress);
    let endPlace = '到达地点：' + this.stringDataFormat(this.state.carDetailData.tagAddress);
    let goTime = '出发时间：' + this.stringDataFormat(moment(this.state.carDetailData.startDate).format('MM-DD HH:mm'));

    let peopleCount
    if (this.state.carDetailData.type == 0){
      peopleCount = '乘车人数：' + this.state.carDetailData.peopleCount + '人';
    } else if (this.state.carDetailData.type == 1) {
      peopleCount = '提供座位：' + this.state.carDetailData.peopleCount + '个';
    }

    let intro = this.state.carDetailData.intro ? this.state.carDetailData.intro : '暂无';

    let adStyle = this.state.showAd ? 'ad-style' : 'ad-invisible';

    return (
      <View className='car-detail-container'>
        <View style='width:0px;height:0px;overflow:hidden;'>
          <Canvas canvasId='share' style='width:750px;height:1334px;position:fixed;left:9000px;'></Canvas>
        </View>
        <View className='car-detail-divider'></View>
        <View className='car-detail-head-container'>
          <AtAvatar  className='car-detail-head-image' image={this.state.carDetailData.headUrl} circle ></AtAvatar >
          <View className='car-detail-head-sub'>
            <Text className='car-detail-name'>{this.state.carDetailData.userName}</Text>
            <Text className='car-detail-name'>{this.state.carDetailData.releaseStrDate}</Text>
          </View>
        </View>
        <View className='car-detail-thin-divider'></View>
        <View className='car-detail-single-container'>
          <Image className='car-detail-single-icon' src={start_icon}></Image>
          <Text className='car-detail-single-text'>{startPlace}</Text>
        </View>
        <View className='car-detail-single-container'>
          <Image className='car-detail-single-icon' src={end_icon}></Image>
          <Text className='car-detail-single-text'>{endPlace}</Text>
        </View>
        <View className='car-detail-single-container'>
          <Image className='car-detail-single-icon-small' src={time_icon}></Image>
          <Text className='car-detail-single-text'>{goTime}</Text>
        </View>
        <View className='car-detail-single-container'>
          <Image className='car-detail-single-icon-small' src={passanger_icon}></Image>
          <Text className='car-detail-single-text'>{peopleCount}</Text>
        </View>
        <View className='car-detail-thin-divider'></View>
        <Text className='car-detail-note' style='margin-left: 20px;color:#666666'>备注：</Text>
        <Text className='car-detail-note' style='margin-left: 40px;color:coral'>{intro}</Text>
        <View className={adStyle}>
          <Ad unitId='adunit-c5ccf5077e093a65' onError={this.onAdError.bind(this)} onLoad={this.onAdLoad.bind(this)}></Ad>
        </View>
        <DetailToolBar itemId={this.state.carDetailData.id} mobileNumber={this.state.carDetailData.mobile}
                       itemType={2} hasCollect={this.state.carDetailData.isCollect}/>
        <View className='car-detail-share'  onClick={this.onSharePost.bind(this)}>
          <Text className='car-detail-share-text'>分享</Text>
          <Text className='car-detail-share-text'>海报</Text>
        </View>
        <AtFloatLayout
          isOpened={this.state.shareShow}
          scrollY
          onClose={this.onShareClose.bind(this)}
          title='分享到朋友圈'
        >
          <View className='detail-share-container'>
            <Image className='detail-share-img' src={this.state.shareTempFilePath}></Image>
            <Button className='detail-share-btn-post' onClick={this.saveSharePic.bind(this)}>保存图片</Button>
            <Text className='detail-share-hint'>保存图片到手机后，您可到朋友圈分享该图片</Text>
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}
